#!/bin/bash

# 定义全局变量
WORKDIR='/opt/jenkins_home'
NewVer=$1
OldVer=`curl -I -s http://localhost:8080/api/python/ | grep "X-Jenkins:" | awk -F':' '{print $2}'`

# 备份旧版本jenkins.war
BackupVersion(){
  # 定义备份目录
  BACKUPDIR="/opt/backup/jenkins_war/$OldVer"
  
  # 停止jenkins服务器
  /opt/script/jenkins.sh stop
  
  # 备份主要配置文件及jenkins.war
  mkdir -p $BAKCUPDIR
  cp $WORKDIR/{jenkins.war,config.xml,updates/default.json} $BACKUPDIR/
}

# 安装新版本jenkins.war
GetNewVersion(){
  # 获取war包
  wget https://mirrors.huaweicloud.com/jenkins/war/${NewVer}/jenkins.war > /dev/null
  
  # 部署war包
  rm -f $WORKDIR/jenkins.war
  mv jenkins.war $WORKDIR/jenkins.war
  
  # 修改配置文件版本号
  sed -i "s#$OldVer#$NewVer#g" $WOKRDIR/config.xml
  
  # 启动jenkins
  /opr/script/jenkins.sh start
}

BackupVersion
GetNewVersion
